import { useState } from 'react'
import { useToast } from '@/hooks/use-toast'

interface RowCopyOptions {
  nameField?: string
  numberField?: string
  remarkField?: string
  idPrefix?: string
}

interface CopiedRowData {
  index: number;
  data: any;
  originalIndex: number;
}

export function useRowCopy(data: any[], options: RowCopyOptions = {}) {
  const { toast } = useToast()
  const [copiedRowsCount, setCopiedRowsCount] = useState(0)
  const [insertedRows, setInsertedRows] = useState<CopiedRowData[]>([])
  
  const { nameField = '设备名称', numberField = '序号', remarkField = '备注' } = options

  // 复制行到剪贴板
  const copyRowToClipboard = (row: any) => {
    const rowData = JSON.stringify(row, null, 2)
    navigator.clipboard.writeText(rowData)
    setCopiedRowsCount(prev => prev + 1)
  }

  // 复制行并插入到表格中
  const duplicateRow = async (row: any, index: number, addDeviceApi?: (d: Partial<any>) => Promise<any>) => {
    // `row` 来自于UI，它的键是中文的，如 "设备ID", "设备表及材料表中的实体对象名称"
    // `addDeviceApi` (即 useUnifiedDevices中的addDevice) 期望的键是英文的，如 "name", "classificationName"
    // 因此，在这里需要进行一次映射转换

    // 从原设备数据中获取专业信息，或者从URL等其他方式推断
    let specialty = row.specialty;
    if (!specialty) {
      // 如果没有专业信息，尝试从当前页面URL推断
      if (typeof window !== 'undefined') {
        const pathname = window.location.pathname;
        if (pathname.includes('/piping')) specialty = '配管专业';
        else if (pathname.includes('/electrical')) specialty = '电气专业';
        else if (pathname.includes('/hvac')) specialty = '暖通专业';
        else if (pathname.includes('/communication')) specialty = '通信专业';
        else if (pathname.includes('/instrumentation')) specialty = '仪表专业';
        else specialty = '配管专业'; // 默认值
      } else {
        specialty = '配管专业'; // 服务端渲染时的默认值
      }
    }

    const newDeviceData = {
      // 从UI的row对象中取值，赋给API期望的字段
      name: `${row.设备表及材料表中的实体对象名称 || ''}_副本`,
      classificationName: row.对应的对象分类标准中的中文名称,
      classificationCode: row.分类码,
      specialty: specialty,
      namingTableId: row.对象命名,
      positionTableId: row.位置信息,
      baseParamsTableId: row.基础参数,
      techSpecTableId: row.技术规格书,
      sequence_number: row.序号,
      remarks: row.备注,
      // 添加原始设备的device_id，用于生成递增序号
      original_device_id: row.displayId || row.设备ID,
    };

    if (addDeviceApi) {
      try {
        const result = await addDeviceApi(newDeviceData);
        // addDeviceApi内部会重新fetch数据，并更新UI状态，所以这里理论上不需要手动更新
        // 但为了即时反馈，可以考虑将返回的device插入，不过这可能导致重复
        // 目前依赖addDeviceApi内部的fetchDevices来刷新
        toast({
          title: "复制成功",
          description: "已新增同类设备，数据将自动刷新。",
        });
      } catch (error) {
        console.error("复制设备失败:", error);
        toast({
          title: "复制失败",
          description: "无法新增同类设备，请检查网络或联系管理员。",
          variant: "destructive",
        });
      }
    }
  };

  // 删除复制的行
  const deleteCopyRow = (index: number, onRowDeleted?: (deletedRowOriginalIndex: number) => void) => {
    const deletedRow = insertedRows[index]
    setInsertedRows(prev => prev.filter((_, i) => i !== index))
    setCopiedRowsCount(prev => prev - 1)

    // 通知删除回调，传递被删除设备的原始索引
    if (deletedRow && onRowDeleted) {
      onRowDeleted(deletedRow.originalIndex)
    }

    toast({
      title: "删除设备成功",
      description: "已删除选中的设备",
    })
  }

  // 删除真实设备（从数据库中删除）
  const deleteRealDevice = async (deviceId: string, deleteDeviceApi?: (deviceId: string) => Promise<boolean>, onRowDeleted?: () => void) => {
    console.log('deleteRealDevice调用:', { deviceId, hasApi: !!deleteDeviceApi });
    
    if (deleteDeviceApi) {
      try {
        const success = await deleteDeviceApi(deviceId);
        console.log('deleteDeviceApi结果:', success);
        
        if (success) {
          if (onRowDeleted) {
            onRowDeleted();
          }
          toast({
            title: "删除设备成功",
            description: "已从数据库中删除设备",
          });
        } else {
          toast({
            title: "删除设备失败",
            description: "无法删除设备，请检查设备是否存在",
            variant: "destructive",
          });
        }
      } catch (error) {
        console.error("删除设备失败:", error);
        toast({
          title: "删除设备失败",
          description: "删除设备时发生错误，请联系管理员",
          variant: "destructive",
        });
      }
    } else {
      toast({
        title: "删除失败",
        description: "删除功能尚未实现",
        variant: "destructive",
      });
    }
  }

  // 清空所有复制的行
  const clearCopiedRows = () => {
    setInsertedRows([])
    setCopiedRowsCount(0)
  }

  // 获取所有数据（包括原始数据和复制的行）
  const getAllData = () => {
    const result = [...data]
    insertedRows.forEach(row => {
      result.splice(row.originalIndex + 1, 0, row.data)
    })
    return result
  }

  return {
    copiedRowsCount,
    copyRowToClipboard,
    duplicateRow,
    clearCopiedRows,
    getAllData,
    deleteCopyRow,
    deleteRealDevice,
    insertedRows
  }
} 